package com.lsh.oms.worker.service.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dangdang.ddframe.job.api.JobExecutionMultipleShardingContext;
import com.dangdang.ddframe.job.plugin.job.type.simple.AbstractSimpleElasticJob;
import com.lsh.ofc.api.dto.SoHeadDTO;
import com.lsh.ofc.api.service.SoService;
import com.lsh.oms.core.enums.ResponsibleType4WG;
import com.lsh.oms.core.enums.TaskStatus;
import com.lsh.oms.core.enums.TaskType;
import com.lsh.oms.core.model.order.OrderRoDetail;
import com.lsh.oms.core.model.order.OrderRoHead;
import com.lsh.oms.core.model.po.OmsTask;
import com.lsh.oms.core.model.push.orderreturn.OrderRoItemsInfo;
import com.lsh.oms.core.model.push.orderreturn.OrderRoPushForm;
import com.lsh.oms.core.proxy.service.WgOrderLossPushProxy;
import com.lsh.oms.core.service.other.RoOrderService;
import com.lsh.oms.core.service.po.OmsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author zhangbiao
 * @date 18/5/16
 * 货损 数据push同步
 * <p>
 * <p>
 * 货损单:
 * 1:oms_TASK获取货损单ID,根据货损单ID 获取Order_Ro_HEAD,发送 订单号Orderid 通过ofc接口获取   [so_id,supplyid]列表
 * 2:根据 supplyid,so_id 过滤 Order_RO_DETAIL
 * 3:其他:第一步 获取获取几条  发送几条push,具体的push地址根据supplierid适配具体URL
 * <p>
 * <p>
 * 注意:
 * 1:签收单接口的用  发货单的arrived_at
 * 2:定损的的arrived_at用order_ro_head.pass_at
 */
@Slf4j
@Component
@Deprecated
public class OrderLossPushTask extends AbstractSimpleElasticJob {

    @Autowired
    private OmsTaskService omsTaskService;

    @Autowired
    private RoOrderService roOrderService;

    @Autowired
    private WgOrderLossPushProxy wgOrderLossPushProxy;

    @Autowired
    private SoService soService;

    @Autowired
    protected OrderPushUrlInfo orderPushUrlInfo;


    @Override
    public void process(JobExecutionMultipleShardingContext shardingContext) {

        List<OmsTask> omsTaskList;
        List<OrderRoHead> orderRoHeadList = new ArrayList<>();
        List<Long> lossOrderCodes = new ArrayList<>();
        OmsTask omsTaskParam = new OmsTask();
        omsTaskParam.setTaskType(TaskType.Bill_RO.getCode());
        omsTaskParam.setTaskStatus(TaskStatus.TASK_UN_DEAL.getCode());
        omsTaskList = omsTaskService.getTasksByFilter(omsTaskParam);
        int handle_succ = 0;
        int handle_skip = 0;
        int head_exist_count;
        int push_request_count = 0;

        int taskCount = omsTaskList.size();
        log.info("货损单:需要处理的货损单数量:" + taskCount);

        if (taskCount > 0) {
            log.info("货损单:开始Push货损单");
            HashMap<Long, Long> orderCodeTaskIdMapping = new HashMap<>();
            log.info("货损单:批量获取货损单操作业务   [组建货损单-OMS任务ID]映射关系");
            for (OmsTask omsTask : omsTaskList) {
                lossOrderCodes.add(Long.valueOf(omsTask.getRefCode()));
                orderCodeTaskIdMapping.put(Long.valueOf(omsTask.getRefCode()), omsTask.getId());
                OrderRoHead orderRoHead = this.roOrderService.getHeadByReturnOrderId(Long.valueOf(omsTask.getRefCode()));
                if (orderRoHead != null) {
                    orderRoHeadList.add(orderRoHead);
                }
            }
            head_exist_count = orderRoHeadList.size();
            log.info("货损单:需要处理的货损单头信息条数:" + head_exist_count);
            //循环处理 返仓单
            for (OrderRoHead orderRoHead : orderRoHeadList) {

                int storege_type = orderRoHead.getStorageTypeId();
                //1 常温  2 冻品
                if (storege_type == 1) {
                    //只处理常温返仓单
                    //根据orderID 调用OFC接口 获取  [supplyid,so_id] 列表
                    List<SoHeadDTO> soHeadDTOs = this.soService.querySignOrders(orderRoHead.getOrderId());
                    HashMap<Integer, String> soID_supplyID_mapping = new HashMap<>();
                    for (SoHeadDTO soHeadDTO : soHeadDTOs) {
                        soID_supplyID_mapping.put(soHeadDTO.getSupplierOrg(), soHeadDTO.getSoCode());
                    }
                    //根据[supplyid,so_id]  过滤Order_SIGN_DETAIL信息
                    List<OrderRoDetail> orderRoDetailList = roOrderService.getOrderRoDetailList(orderRoHead.getReturnOrderId());
                    HashMap<Integer, List<OrderRoDetail>> hashMapGroupBySupplyID = new HashMap<>();
                    for (OrderRoDetail orderRoDetail : orderRoDetailList) {
                        List<OrderRoDetail> orderRoDetailList1 = hashMapGroupBySupplyID.get(orderRoDetail.getSupplierOrg());
                        if (orderRoDetailList1 == null) {
                            orderRoDetailList1 = new ArrayList<>();
                            orderRoDetailList1.add(orderRoDetail);
                            hashMapGroupBySupplyID.put(orderRoDetail.getSupplierOrg(), orderRoDetailList1);
                        } else {
                            hashMapGroupBySupplyID.get(orderRoDetail.getSupplierOrg()).add(orderRoDetail);
                        }
                    }

                    //PUSH结果集合 用于计算基于签收单ID维度的事务完成情况
                    List<Integer> ret_list = new ArrayList<>();
                    for (Integer supplyorid : hashMapGroupBySupplyID.keySet()) {
                        //订单总额
                        BigDecimal wg_price = new BigDecimal("0");
                        wg_price.setScale(6);
                        List<OrderRoDetail> orderRoDetailList1 = hashMapGroupBySupplyID.get(supplyorid);
                        log.info("货损单:分组后的翻仓单详细信息列表 supplyid:" + supplyorid + "  orderRoDetailList1:" + JSON.toJSONString(orderRoDetailList1));

                        //按照supplyid SO_ID维度进行遍历    组装json报文  发送
                        OrderRoPushForm orderRoPushForm = new OrderRoPushForm();
                        List<OrderRoItemsInfo> items = new ArrayList<>();
                        for (OrderRoDetail orderRoDetail : orderRoDetailList1) {
                            log.info("货损单:货损单ID" + orderRoDetail.getReturnOrderId() + "  货损单明细信息:" + JSON.toJSONString(orderRoDetail));
                            wg_price = wg_price.add(orderRoDetail.getMoney());
                            OrderRoItemsInfo orderRoItemsInfo = new OrderRoItemsInfo();
                            JSONObject jsonObjectExt = JSONObject.parseObject(orderRoDetail.getExt());
                            String wm_code = (String) jsonObjectExt.get("wm_code");
                            //BigDecimal origin_price=(BigDecimal) jsonObjectExt.get("origin_price");
                            BigDecimal saled_price = jsonObjectExt.getBigDecimal("saled_price");

                            orderRoItemsInfo.setSale_unit(orderRoDetail.getSaleUnit().intValue());
                            orderRoItemsInfo.setQty(orderRoDetail.getQty().intValue());
                            orderRoItemsInfo.setReal_qty(orderRoDetail.getRealQty().intValue());
                            orderRoItemsInfo.setGoods_name(orderRoDetail.getSkuName());
                            orderRoItemsInfo.setGoods_id(wm_code);
                            orderRoItemsInfo.setPrice(saled_price.floatValue());
                            items.add(orderRoItemsInfo);
                        }
                        orderRoPushForm.setItems(items);
                        orderRoPushForm.setReturn_id(String.valueOf(orderRoHead.getReturnOrderId()));
                        orderRoPushForm.setSo_id(soID_supplyID_mapping.get(supplyorid));
                        orderRoPushForm.setOrder_id(String.valueOf(orderRoHead.getOrderId()));
                        orderRoPushForm.setSend_id(String.valueOf(orderRoHead.getShippingOrderId()));
                        orderRoPushForm.setReturn_type(orderRoHead.getReturnOrderType());
                        orderRoPushForm.setPrice(orderRoHead.getMoney().floatValue());
                        orderRoPushForm.setArrived_at(String.valueOf(orderRoHead.getPassAt()));
                        orderRoPushForm.setZone_id(String.valueOf(orderRoHead.getZoneId()));
                        orderRoPushForm.setFin_code("");
                        orderRoPushForm.setDriver_fin_code("");
                        //承担类型：2 链商承担，3是司机承担  push给文固是:承担类型1:链商，2司机
                        orderRoPushForm.setResponsible_type(exchangeRType(orderRoHead.getType()));
                        orderRoPushForm.setResponsible_person("");
                        String data = JSON.toJSONString(orderRoPushForm);
                        String pushUrl = orderPushUrlInfo.getPushUrl();
                        String responseData = wgOrderLossPushProxy.push(pushUrl + "/api/so/loss", data, orderRoHead.getVenderId());
                        push_request_count++;
                        JSONObject jsonObjectResponse = JSON.parseObject(responseData);
                        //请求push
                        int ret = jsonObjectResponse.getInteger("ret").intValue();
                        ret_list.add(ret);
                    }
                    //更新OMS-TASK状态
                    int result = 0;
                    for (int ret : ret_list) {
                        result += ret;
                    }
                    OmsTask omsTask = new OmsTask();
                    if (result == 0) {
                        handle_succ++;//事务成功
                        omsTask.setId(orderCodeTaskIdMapping.get(orderRoHead.getReturnOrderId()));
                        omsTask.setTaskStatus(TaskStatus.TASK_DEAL_SUCCESS.getCode());
                        int handleCount = omsTaskService.update(omsTask);
//                        System.out.println(omsTask.getId() + "货损单:状态更新影响条数:" + handleCount);
                    } else {
                        omsTask.setId(orderCodeTaskIdMapping.get(orderRoHead.getReturnOrderId()));
                        omsTask.setTaskStatus(TaskStatus.TASK_DEAL_FAIL.getCode());
                        omsTaskService.update(omsTask);
//                        System.out.println("货损单:Push任务异常,OMS TASK ID:" + orderCodeTaskIdMapping.get(orderRoHead.getReturnOrderId()) + "  返仓单ID:" + orderRoHead.getReturnOrderId());
                    }
                } else {
                    handle_skip++;
                    log.info("货损单:冻品签收单数据不同步,货损单ID:" + orderRoHead.getReturnOrderId());
                }
            }
            log.info("货损单:货损单信息推送完毕,总共:" + taskCount + "单,有效Head信息:" + head_exist_count + "单,成功处理:" + handle_succ + "单[常温],跳过处理:" + handle_skip + "单[冻品],共推送" + push_request_count + "次");

        } else {
            log.info("货损单:系统没有需要处理的 [货损单].");
        }

    }


    /**
     * 链商与文固的责任码转换
     *
     * @param RType
     * @return
     */
    private Integer exchangeRType(int RType) {
        Integer WGType = ResponsibleType4WG.UNKNOW.getCode();
        if (RType == 2) {
            WGType = ResponsibleType4WG.LSH.getCode();
        } else if (RType == 3) {
            WGType = ResponsibleType4WG.DRIVER.getCode();
        }
        return WGType;
    }
}
